package com.etymgiko.spaceshipshop.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Prevents not authorized access to resources. 
 *
 * @author Ivan Holub
 */
public class LoginFilter implements Filter {

    /**
     * Resources that must be accessed in session.
     */
    private String [] authorizedPaths = new String [] {
            "/newshipaction.do",
            "/newship.do",
            "/availableships.do",
            "/myships.do",
            "/buyship.do",
            "/sellship.do"};

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;

        boolean isAuthorizedPath = false;
        String servletPath = req.getServletPath();
        for (String path : authorizedPaths) {
            if (servletPath.startsWith(path)) {
                isAuthorizedPath = true;
                break;
            }
        }

        boolean isRequestValid = true;
        if (isAuthorizedPath) {
            HttpSession session = req.getSession(false);
            if (session != null) {
                isRequestValid = session.getAttribute("user") != null;
            } else {
                isRequestValid = false;    
            }
        }

        if (!isRequestValid) {
            // redirects to index.jsp
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendRedirect("index.jsp");
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void destroy() {
    }
}
